package com.sh.栈;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class 最小栈 {
    public static void main(String[] args) {

        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());
        minStack.pop();
        System.out.println(minStack.getMin());
        minStack.top();
        System.out.println(minStack.getMin());

    }


    static class MinStack {
        private Node top = null;
        private int minNum;  // 最小值

        public MinStack() {
            top = new Node(Integer.MAX_VALUE);
            minNum = Integer.MAX_VALUE;
        }

        public void push(int val) {
            Node node = new Node(val);
            minNum = val < minNum ? val : minNum;
            node.next = top;
            top = node;
        }

        public void pop() {
            if (top.val == getMin()) {
                top = top.next;
                Node temp = top;
                minNum = Integer.MAX_VALUE;
                while (temp != null) {
                    minNum = temp.val < minNum ? temp.val : minNum;
                    temp = temp.next;
                }
                return;
            }
            top = top.next;
        }

        public int top() {
            return top.val;
        }

        public int getMin() {
            return minNum;
        }


        class Node {
            Node next;
            int val;

            public Node(int n) {
                this.val = n;
            }
        }
    }


}

